package com.atsmart.app.utils;

import java.io.File;

import com.atsmart.app.BizApp;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

public class UpdateUtils {
	
	private static final String TAG = "UpdateUtils";
	
	private static String UPDATE_SERVERAPK = "biz.apk";
	private static UpdateUtils instance;
	public static UpdateUtils getInstance() {
		if(null == instance){
			instance = new UpdateUtils();
		}
		return instance;
	}
	
	/**
	 * @return 网络判断
	 */
	public boolean isNetwork(){
		return (BizApp.getInstance().isNetworkAvailable() || BizApp.getInstance().isWiFiActive())&&BizApp.getInstance().keeping;
	}
	
	/**
	 * @return SD卡是否存在
	 */
	public boolean isSD(){
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
	}
	
	/**
	 * @return SD卡剩余空间
	 */
	public long getSDFreeSize(){
		if(isSD()){
			File file = Environment.getExternalStorageDirectory();
			StatFs sf = new StatFs(file.getPath());
			// 获取单个数据块的大小(Byte)
			long blockSize = sf.getBlockSize();
			// 空闲的数据块的数量
			long freeBlocks = sf.getAvailableBlocks();
			// 返回SD卡空闲大小
			 return freeBlocks * blockSize; //单位Byte
			// return (freeBlocks * blockSize)/1024; //单位KB
		//	return (freeBlocks * blockSize) / 1024 / 1024; // 单位MB
		}else{
			return -1;
		}
	}
	
	/**
	 * 获得版本号
	 */
	public int getVerCode(Context context) {
		int verCode = -1;
		try {
			verCode = context.getPackageManager().getPackageInfo(
					"com.atsmart.app", 0).versionCode;
		} catch (NameNotFoundException e) {
			Log.e(TAG, "版本号获取异常"+e.getMessage());
		}
		return verCode;
	}

	/**
	 * 获得版本名称
	 */
	public String getVerName(Context context) {
		String verName = "";
		try {
			verName = context.getPackageManager().getPackageInfo(
					"com.atsmart.app", 0).versionName;
		} catch (NameNotFoundException e) {
			Log.e(TAG, "版本名称获取异常" + e.getMessage());
		}
		return verName;
	}
	
	/**
	 * 安装应用
	 */
	public void update(Context context) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(
				Uri.fromFile(new File(Environment.getExternalStorageDirectory()
						.toString() + "/atsmart", UPDATE_SERVERAPK)),
				"application/vnd.android.package-archive");
		context.startActivity(intent);

	}
}
